<template>
  <v-container class="auth-container auth-text" fluid>
    <v-row justify="center">
      <v-col cols="12" sm="8" md="10" lg="8">
        <v-card class="elevation-6">
          <v-row no-gutters>
            <!-- 左侧图片 -->
            <v-col cols="12" md="6" class="d-none d-md-flex">
              <v-img src="../ico/logo.png" alt="Logo" height="100%" cover class="logo-img"></v-img>
            </v-col>

            <!-- 右侧登录表单 -->
            <v-col cols="12" md="6" class="pa-6">
              <v-card-title class="text-h5 grey lighten-2"> 登录 </v-card-title>
              <v-card-text>
                <v-form @submit.prevent="login">
                  <v-text-field 
                    v-model="identifier" 
                    label="用户名或邮箱" 
                    required
                    :disabled="loading"
                  ></v-text-field>
                  <v-text-field
                    v-model.number="captchaData.code"
                    label="验证码"
                    type="number"
                    required
                    :disabled="loading"
                  ></v-text-field>
                  <v-btn 
                    type="submit" 
                    color="primary" 
                    block 
                    class="mt-4"
                    :loading="loading"
                    :disabled="loading"
                  > 
                    {{ loading ? '登录中...' : '登录' }}
                  </v-btn>
                </v-form>
                                  <v-btn
                    type="button"
                    color="secondary"
                    block
                    class="mt-2"
                    @click="getVerificationCode"
                    :loading="codeLoading"
                    :disabled="codeLoading || loading"
                  >
                    {{ codeLoading ? '发送中...' : '申请验证码' }}
                  </v-btn>

                  <!-- 注册链接 -->
                  <div class="text-center mt-4">
                    <v-btn
                      variant="text"
                      color="primary"
                      @click="goToRegister"
                      :disabled="loading"
                    >
                      没有账号？立即注册
                    </v-btn>
                  </div>

                  <v-btn color="secondary" @click="$router.push('/admin/login')" class="ml-2">
                    <v-icon start>mdi-account-key</v-icon>管理员登录
                  </v-btn>
                </v-card-text>
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>

    <!-- 成功提示 -->
    <v-snackbar v-model="showSuccess" color="success">
      {{ successMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showSuccess = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>

    <!-- 错误提示 -->
    <v-snackbar v-model="showError" color="error">
      {{ errorMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showError = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const router = useRouter()

// 初始化标识符（用户名或邮箱）
const identifier = ref('')

// 初始化验证码数据
const captchaData = ref({
  code: null,
})

// 加载状态
const loading = ref(false)
const codeLoading = ref(false)

// 提示消息
const showSuccess = ref(false)
const showError = ref(false)
const successMessage = ref('')
const errorMessage = ref('')

// 登录方法
const login = async () => {
  if (!identifier.value || !captchaData.value.code) {
    showErrorMessage('请填写完整的登录信息')
    return
  }

  try {
    loading.value = true
    
    // 提交验证码进行验证
    const captchaResponse = await proxy.$api.verifyLoginCode(captchaData.value)
    console.log('登录成功:', captchaResponse.data)

    // 显示成功消息
    showSuccessMessage('登录成功！正在跳转...')
    
    // 延迟跳转，让用户看到成功消息
    setTimeout(() => {
      router.push('/')
    }, 1500)
    
  } catch (error) {
    console.error('登录失败:', error)
    showErrorMessage('登录失败，请检查验证码是否正确')
  } finally {
    loading.value = false
  }
}

// 申请验证码方法
const getVerificationCode = async () => {
  if (!identifier.value) {
    showErrorMessage('请先输入用户名或邮箱')
    return
  }

  try {
    codeLoading.value = true
    const response = await proxy.$api.loginUser(identifier.value)
    console.log('验证码申请结果:', response.data)
    showSuccessMessage('验证码已发送，请查收！')
  } catch (error) {
    console.error('验证码申请失败:', error)
    showErrorMessage('验证码申请失败，请重试')
  } finally {
    codeLoading.value = false
  }
}

// 显示成功消息
const showSuccessMessage = (message) => {
  successMessage.value = message
  showSuccess.value = true
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 显示错误消息
const showErrorMessage = (message) => {
  errorMessage.value = message
  showError.value = true
}
</script>

<style scoped>
.auth-container {
  max-width: 80%;
  margin-top: 3rem;
}
</style>
